<?php

/**
 * Created by PhpStorm.
 * User: Jie
 * Date: 4/12/2016
 * Time: 4:53 PM
 */
class MobileregisterController extends \Core_BaseCtl {

    //文件缓存
    public $cache;

    //初始化
    public function init() {
        parent::init();
        //缓存开启
        $cache_config = $this->config['cache'];
        $this->cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
    }

    //注册方法
    public function registerAction() {
        if (isset($_GET['mobile'])) {
            $mobile = $this->getg('mobile');
            $session_name = 'mcode_' . $mobile;
        } else {
            return false;
        }
        if (isset($_GET['mcode'])) {
            $code = $this->getg('mcode');
        } else {
            return false;
        }

        //读取session中数据
        $server_data = Tools_help::getSession($session_name);

        //判断缓存时间是否存在
        if (!isset($server_data['time']) || empty($server_data['time'])) {
            $data = array(
                'time' => time(),
                'code' => $code
            );
            //将content的值保存在session中
            ini_set('session.gc_maxlifetime', 40);
            Tools_help::setSession($session_name, $data);
        }
        //刷新一次数据
        $server_data = Tools_help::getSession($session_name);
        //将新验证码保存在session中
        $new_data = array(
            'time' => $server_data['time'],
            'code' => $code
        );
        ini_set('session.gc_maxlifetime', 40);
        Tools_help::setSession($session_name, $new_data);
        $server_data = Tools_help::getSession($session_name);

        //如果得到手机号
        if (!empty($mobile)) {
            if (($server_data['time'] + 300) < time()) {
                //将获取的缓存时间转换成时间戳加上300s后与当前时间比较，小于当前时间即为过期
                //unset($_SESSION[$session_name]);
                Tools_help::setSession($session_name,null);
                echo '<script>alert("验证码已过期，请刷新重新获取！");</script>';
                exit;
            } else {
                $code = $server_data['code'];

                // 以下是用于发送短信的操作
                $flag = $this->sendMessageToUser($mobile, $code);
                if (!$flag) {
                    echo json_encode(array(
                        'result' => 'false',
                        'content' => '发送失败'
                    ));
                    exit;
                } else {
                    echo json_encode(array(
                        'result' => 'true',
                        'content' => '发送成功'
                    ));
                    exit;
                }
            }
        }
    }

    //发送短信方法

    public function sendMessageToUser($mobile, $code)
    {
        $message = '您本次的登录验证码是：'. $code .',请不要轻易告诉别人。[大发搬家公司]';
        $url = "http://101.227.249.44:8181/api/mt.php?eid=110079&key=af2fa8448e75d23d55f945ded26e2fa9&mobile=$mobile&message=$message";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        curl_close($ch);

        if ($data == 'E4007') {
            //E3006
            return true;
        } else {
            return false;
        }
    }

    //短信验证方法
    public function checkMessageCodeAction() {
        $code = 0;
        $server_code = 1;
        $name = '';
        $id = 0;

        if (isset($_GET['code'])) {
            $code = $this->getg('code');
        }
        if (isset($_GET['mobile'])) {
            $mobile = $this->getg('mobile');
            $name = 'mcode_' . $mobile;
        }
        if (Tools_help::getSession($name)) {
            // 对比服务器中的验证码
            $server_code = Tools_help::getSession($name);
            $server_code = $server_code['code'];
            if ($code == $server_code) {
                //登录成功，写入数据库
                //清除session
                Tools_help::setSession('mcode_' . $mobile, NULL);
                //输出回调地址
                echo json_encode(array(
                    'result' => 'true',
                    'weixinurl' => $this->generateMWxUrl($mobile)
                ));
                exit;
            } else {
                // 验证码不正确，返回结果
                echo json_encode(array('result' => 'false1'));
                exit;
            }
        } else {
            // 手机号不存在，返回结果
            echo json_encode(array('result' => 'false2'));
            exit;
        }
    }

    //手机登录页面
    public function loginAction() {
        $pageTitle = '用户注册';
        $loginUrl = $this->generateWxUrl();

        $this->_view->assign('pageTitle', $pageTitle);
        $this->_view->assign('loginUrl', $loginUrl);
    }

    //测试方法
    public function testAction() {
        //$user = new WxuserModel();
        //echo $user->generateUserName();
        //$user->recordMWxUserInfo('o3QGWv-NENhBiDjLjpHcE2K_FZFI','13392789730');
        //$user->recordMWxUserInfo('o3QGWv-NENhBiDjLjpHcE2K_FZFI','13725263463');
        //Tools_help::setSession('openid','o3QGWv-NENhBiDjLjpHcE2K_FZFI');

        $orderModel = new OrderModel();
        $res = $orderModel->getOrderInTime('1461135407','1463558202');

        var_dump($res);
        exit;
    }

    // 生成微信登陆地址
    public function generateWxUrl() {
        //读取配置文件
        $config = \Yaf_Registry::get('configarr');
        $this->myToken = $config['wechat']['myToken'];

        //微信应用id
        $appId = $this->getAppInfo();
        //回调地址
        //读取配置文件
        $config = \Yaf_Registry::get('configarr');
        $website = $config['weisite']['address'];
        $redirect_uri = $website . '/weixinlogin/redirect';
        $redirect_uri = urlencode($redirect_uri);
        //作用类型snsapi_userinfo高级获取用户信息
        $scope = 'snsapi_userinfo';
        //state
        $state = '333';
        //url
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=$state#wechat_redirect";

        //$this->_view->assign('url',$url);
        return $url;
    }

    // 生成手机+微信登陆地址
    public function generateMWxUrl($phone) {
        //读取配置文件
        $config = \Yaf_Registry::get('configarr');
        $this->myToken = $config['wechat']['myToken'];

        //微信应用id
        $appId = $this->getAppInfo();
        //回调地址
        //读取配置文件
        $config = \Yaf_Registry::get('configarr');
        $website = $config['weisite']['address'];
        $redirect_uri = $website . "/weixinlogin/mobileredirect/phonenum/$phone";
        $redirect_uri = urlencode($redirect_uri);
        //作用类型snsapi_userinfo高级获取用户信息
        $scope = 'snsapi_base';
        //state
        $state = '333';
        //url
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=$state#wechat_redirect";

        //$this->_view->assign('url',$url);
        return $url;
    }

    //获取公众号的app信息
    public function getAppInfo() {
        //获取微信账号信息
        //读取配置文件
        $config = \Yaf_Registry::get('configarr');
        if(isset($config['wechat'])) {
            $appId = $config['wechat']['appid'];
            return $appId;
        } else {
            return null;
        }
    }

    //退出方法
    public function logoutAction() {
        Tools_help::setSession('openid',null);

        $content = '退出成功';
        $url = '/mobileregister/login';
        $this->redirect(Tools_help::url("redirect/index?c=$content&u=$url"));
        exit;
    }

    //用户信息页面
    public function userInfoAction() {

        $user = new WxuserModel();
        $pageTitle = '我的用户';
        //读取配置文件
        $config = \Yaf_Registry::get('configarr');
        $website = $config['weisite']['address'];

        $openId= Tools_help::getSession('openid');
        $data = $user->checkWUserExist($openId);
        if ($data) {
            $this->_view->assign('username', $data['username']);
        } else {
//            $content = '尚未登陆，请登录';
//            $url = '/mobileregister/login';
//            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            $this->redirect(Tools_help::url("mobileregister/login"));
        }

        $this->_view->assign('website',$website);
        $this->_view->assign('pageTitle', $pageTitle);
    }
    
    //订单列表
    public function orderListAction() {
        $openid = Tools_help::getSession('openid');
        if ($openid) {
            $orderModel = new OrderModel();
            $list = $orderModel->getLists(array('where' => array('openID' => $openid, 'order_place' => 1), 'order' => 'order_id desc'));
            foreach ($list as $k => $v) {
                $list[$k]['carrydate'] = date('Y-m-d ', $v['carrydate']);
                if ($v['order_state'] == 1) {
                    $list[$k]['state'] = '已付定金 ' . $v['already_price'];
                } else if ($v['order_state'] == -2) {
                    $list[$k]['state'] = '已退款';
                } else if ($v['order_state'] == 0){
                    $list[$k]['state'] = '未付款';
                } else if ($v['order_state'] == 2){
                    $list[$k]['state'] = '已派工';
                } else if ($v['order_state'] == 3){
                    $list[$k]['state'] = '已完成';
                }
            }
        }
        $this->_view->assign('openid', $openid);
        $this->_view->assign('list', $list);
        $this->_view->assign('pageTitle', '订单列表');
        $this->_view->assign('returnUrl', Tools_help::url('Mobileregister/userinfo'));
    }

    //订单信息
    public function orderInfoAction() {
        $openid =  Tools_help::getSession('openid');
        $order_number = $this->getg('order_number', '');
        if (empty($openid) || empty($order_number)) {
            $content = "访问有误！";
            $url = "/Mobileregister/uesrinfo";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
        }
        $orderModel = new OrderModel();
        $info = $orderModel->select(array('where' => array('openid' => $openid, 'order_number' => $order_number)));

        $info['carrydate'] = date('Y-m-d', $info['carrydate']);
        $info['createtime'] = date('Y-m-d H:i:s', $info['createtime']);
        //$info['deposit_price'] = ceil($info['total_price'] * ($info['deposit_rate']/100)).'.00 ';

        $serviceModel = new ServiceModel();
        switch ($info['client_type']) {
            case 'C':$info['client_type'] = '个人';
                break;
            case 'Q':$info['client_type'] = '企业';
                break;
            case 'Z':$info['client_type'] = '政府';
                break;
            case 'O':$info['client_type'] = '其他';
                break;
        }
//        echo "<pre>";
//        print_r($info);exit;
        $this->_view->assign('openid', $openid);
        $this->_view->assign('order_number', $order_number);
        $this->_view->assign('info', $info);
        $this->_view->assign('pageTitle', '订单信息');
        $this->_view->assign('returnUrl', Tools_help::url('Mobileregister/orderlist'));
    }

    //修改订单
    public function orderEditAction() {
        $openid =  Tools_help::getSession('openid');
        $order_number = $this->getg('order_number', '');
        if (empty($openid) || empty($order_number)) {
            $content = "访问有误！";
            $url = "/Mobileregister/orderinfo/order_number/$order_number/openid/$openid";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
        }
        $orderModel = new OrderModel();
        $info = $orderModel->select(array('where' => array('openid' => $openid, 'order_number' => $order_number)));
        $info['openid'] = $openid;
        $info['order_number'] = $order_number;
        $this->_view->assign('info', $info);
        $this->_view->assign('pageTitle', '订单列表');
        $this->_view->assign('returnUrl', Tools_help::url("Mobileregister/orderinfo/order_number/$order_number/openid/$openid"));
    }

    //
    public function feeInfoAction() {
        $openid = Tools_help::getSession('openid');
        $order_number = $this->getg('order_number', '');
        
        if (empty($openid) || empty($order_number)) {
            $content = "访问有误！";
            $url = "/Mobileregister/orderinfo/order_number/$order_number/openid/$openid";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
        }
        $orderModel = new OrderModel();
        $info = $orderModel->select(array('where' => array('openid' => $openid, 'order_number' => $order_number)));
        $fee['price_list'] = json_decode($info['price_list']);
        
        if ($info['meal_type'] == 1) {
            $fee['content_list'] = json_decode($info['content_list']);
            $fee['content_list'][0] = htmlspecialchars_decode($fee['content_list'][0]);
        }else{
            $fee['content_list'] = json_decode($info['content_list']);
        }

        $fee['option_list'] = json_decode($info['option_list']);
        $fee['total_price'] = $info['total_price'];
        $fee['deposit_price'] = ceil($info['total_price'] * ($info['deposit_rate'] / 100));
        $fee['meal_type'] = $info['meal_type'];
        //print_r($fee);exit;
        $this->_view->assign("fee", $fee);
        $this->_view->assign('pageTitle', '费用信息');
        $this->_view->assign('returnUrl', Tools_help::url("Mobileregister/orderinfo/order_number/$order_number/openid/$openid"));
    }

    public function modelsInfoAction() {
        $openid =  Tools_help::getSession('openid');
        $order_number = $this->getg('order_number', '');
        if (empty($openid) || empty($order_number)) {
            $content = "访问有误！";
            $url = "/Mobileregister/orderinfo/order_number/$order_number/openid/$openid";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
        }
        $orderModel = new OrderModel();
        $info = $orderModel->select(array('where' => array('openid' => $openid, 'order_number' => $order_number),'field'=>array('driver_name','driver_phone','car_number','foreman')));
       // print_r($info);exit;
        $this->_view->assign('info', $info);
        $this->_view->assign('pageTitle', '车辆信息');
        $this->_view->assign('returnUrl', Tools_help::url("Mobileregister/orderinfo/order_number/$order_number/openid/$openid"));
    }

    //设置
    public function resetingAction() {

        // 处理Post
        if ($this->getRequest()->isPost()) {
            // 获取所有post数据
            $pdata = $this->getAllPost();

            $openid = Tools_help::getSession('openid');
            $order_number = $pdata['order_number'];
            $orderModel = new OrderModel();

            $update = array();
            $update['client_name'] = $pdata['client_name'];
            $update['client_phone'] = $pdata['client_phone'];
            $update['start_address'] = $pdata['start_address'];
            $update['arrive_address'] = $pdata['arrive_address'];
            $update['remark'] = $pdata['remark'];
            $update['already_edit'] = 1;

            // 验证
            $result = $orderModel->validation->validate($update, 'only_reseting');

            // 通过验证
            if ($result) {

                // 入库前数据处理
                $result = $orderModel->update(array('order_number' => $order_number, 'openid' => $openid), $update);

                if ($result) {
                    // 提示信息并跳转到列表
                    $content = "修改成功！";
                    $url = "/Mobileregister/orderinfo/order_number/$order_number";
                    $this->redirect(Tools_help::url("redirect/index?c=$content&u=$url"));exit;
                } else {
                    // 出错
                    $content = "插入有误！";
                    $url = "/Mobileregister/orderinfo/order_number/$order_number";
                    $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
                }
            } else {

                // 验证失败
                $content = "参数有误！";
                $url = "/Mobileregister/orderinfo/order_number/$order_number/openid/$openid";
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            }
        } else {
            $content = "非法操作！";
            $url = "/Mobileregister/userinfo";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
        }
        exit;
    }
    
    //退款流程
    public function weixinApiRefund() {
        return true;
    }
    
    public function fetchDataAction() {
        $cache_config = $this->config['cache'];
        $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
        
        
        
        $postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : '';
        libxml_disable_entity_loader(true);


        //实例化xml对象
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
        //print_r($postObj);
        //$cache->set('payinfo',$postStr);
        $order_number = (string)$postObj->out_trade_no;
        $result_code = (string)$postObj->result_code;
        $time_end = strtotime($postObj->time_end);
        $cash_fee = (int)$postObj->cash_fee;
        $openid = (string)$postObj->openid;
        $orderModel = new OrderModel();
        $state = $orderModel->select(array('field'=>array('order_state'),'where'=>array('order_number'=>$order_number)));
        $cache->set('test',$openid);
        if (!empty($result_code) && $result_code == 'SUCCESS' && $state['order_state'] == '0') {

            //改变状态
            $update = array();
            
            //核销卡券
            if($postObj->attach != false){
                $card = (string)$postObj->attach;
                $card = json_decode($card,true);
                
                Yaf_Loader::import(APP_PATH . 'library/Weixin/wechatCard.php');
                $weixincard = new wechatCard();
                $weixincard->consumeCard($card['card_code']);       
                $update['card_fee'] = number_format(($card['card_fee']/100),2);
                $update['card_title'] = $card['card_title'];
            }
            
            $update['already_price_time'] = $time_end;
            $update['already_price'] = $cash_fee/100;
            $update['order_state'] = 1;
            $rs = $orderModel->update(array('order_number' => $order_number), $update);
            //print_r($rs);exit;
            //发送模版消息
            $data = array();
            $data['order_number'] = $order_number;
            $data['cash_fee'] = $cash_fee/100;
            $data['time_end'] = date("Y-m-d H:i:s",$time_end);
           $this->sendTemp(1,$data,$openid);
        }

        exit;
    }
    
    protected function sendTemp($type, $data, $openid) {
//        $data['order_number'] = 'fdsfsafa';
//        $data['cash_fee'] = 0.01;
//        $data['time_end'] = time();
//        //unset($_SESSION['access_token']);
        Yaf_loader::import(APP_PATH . 'library/Weixin/weixinTemplate.class.php');
        $token = Tools_help::getToken();
        $template_obj = new weixinTemplate($token);
        if ($type == 1) {
            $data_send = array(
                'touser' => $openid,
                'template_id' => 'q61I9d85kuo3Kjrh-Fly2Y1sYLMSFPX-s22PmdJKAH4',
                'url' =>  'http://www.dafabanjia888.com/mobileregister/userinfo',
                'topcolor' => '#00A600',
                'data' => array(
                    'first' => array(
                        'value' => '大发起重公司消息',
                        'color' => '#173177'
                    ),
                    'keyword1' => array(
                        'value' => '搬运服务',
                        'color' => '#000000'
                    ),
                    'keyword2' => array(
                        'value' => $data['order_number'],
                        'color' => '#173177'
                    ),
                    'keyword3' => array(
                        'value' => '1',
                        'color' => '#173177'
                    ),
                    'keyword4' => array(
                        'value' => $data['cash_fee'],
                        'color' => '#173177'
                    ),
                    'keyword5' => array(
                        'value' => $data['time_end'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => '感谢使用我们的服务，我们致力于成为地球最快的搬家公司',
                        'color' => '#173177'
                    ),
                ),
            );
        } else {
            $data_send = array(
                'touser' => $openid,
                'template_id' => '6T4pAnetgJZCayvQ5an31eMPDO_I_v_zuZZul7YBqSY ',
                'url' => 'www.qq.com ',
                'topcolor' => '#00A600',
                'data' => array(
                    'first' => array(
                        'value' => '大发起重公司消息',
                        'color' => '#173177'
                    ),
                    'keyword1' => array(
                        'value' => '00665555',
                        'color' => '#000000'
                    ),
                    'keyword2' => array(
                        'value' => 'fuck wx',
                        'color' => '#000000'
                    ),
                    'remark' => array(
                        'value' => '感谢使用我们的服务，我们致力于成为地球最快的搬家公司',
                        'color' => '#173177'
                    ),
                ),
            );
        }
        $send_msg = $template_obj->sendMessageTemplate($data_send);
        $cache_config = $this->config['cache'];
        $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);      
        $cache->set('payinfo',$send_msg);
        $cache->set('test2',$openid);
    }

    public function showDataAction() {
        $cache_config = $this->config['cache'];
        $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
        echo $cache->get('payinfo');
        exit;
    }

}
